package com.echo.boot.sync.interview;

import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA
 * Created By CQ
 * Date: 2020/4/16
 * Time: 23:25
 */
public class T07_00_sync_wait_notify {
    private static volatile boolean t2Started = false;

    public static void main(String[] args) {
        Object o = new Object();
        char[] aI = "ABCDEFG".toCharArray();
        char[] aC = "1234567".toCharArray();

        new Thread(() -> {
            synchronized (o) {
                while (!t2Started) {
                    try {
//                        o.notify();
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                for (char c : aI) {
                    System.out.println(c);
                    try {
                        o.notify();
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                o.notify();
            }
        }, "t1").start();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(4);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            latch.countDown();
            synchronized (o) {
                for (char c : aC) {
                    t2Started = true;
                    System.out.println(c);
                    try {
                        o.notify();
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                o.notify();
            }
        }, "t2").start();
    }
}
